//
//  InventoryViewController.m
//  CS Inventory Manager
//
//  Created by Ian Smith on 2/10/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//
//  Wasn't sure where to put this so I will mention it at the top: in order to tell which Type the user selected on the previous level, just look at self.title
//  It will be set to the name of the Type. Use this to generate the list of items that need to be displayed at this level

#import "InventoryViewController.h"
#import "Item.h"
#import "ItemDetailViewController.h"
#import "EditItemDetailViewController.h"

@interface InventoryViewController () {
    
    Item *addNew;
}
@end

@implementation InventoryViewController

@synthesize type;

- (void)awakeFromNib
{
    self.clearsSelectionOnViewWillAppear = YES;
    self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
    [super awakeFromNib];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    for (int x = 0; x < type.items.count; ++x) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    // load the items
    NSLog(@"InventoryViewController: Recieved Type named: %@",[type name]);

    [self setTitle:[type manufacturerAndName]];
    
    self.detailViewController = (ItemDetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
}

-(void)viewDidAppear:(BOOL)animated
{
    
    [self.detailViewController setDelegate:self];
    
    //Adding this here to allow table to automatically display changes made through local edits
    [self.tableView reloadData];
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    if (editing) {
        //Do stuff going into the editing view
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItem:)];
    }
    else {
        self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;
        //Do stuff coming out of the editing view
        //WRITE TO DATABASE HERE
    }
}

//Function that responds to a tap on the "Add" button while in editing view
-(void)addItem:sender {
    Item *newItem = [[Item alloc] init];
    [newItem setMyType:type];
    
    // go ahead and add to the array -- this needs to be moved to the marker I left in the EditItemDetailViewController
    [[type items] addObject:newItem];
    
    [self performSegueWithIdentifier:@"Add" sender:newItem];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return type.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    // Configure the cell...
    Item *item = type.items[indexPath.row];
    cell.textLabel.text = [item model];
    cell.detailTextLabel.text = [item serialNo];
    
    NSLog(@"We're here %@ & %@",[item model],[item serialNo]);
    

    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        // make the web call to delete
        // set all params for URL
        NSString *uid = [NSString stringWithFormat:@"%d", [[type.items objectAtIndex:indexPath.row] itemId]];
        
        // generate the URL and use %20 encoding
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/item.php?secret=pass&id=%@",uid];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"The url is: >>>>>%@<<<<<", final);
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        
        // delete locally too
        [type.items removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    EditItemDetailViewController *nextController = segue.destinationViewController;
    nextController.theItem = sender;
    [nextController setDelegate: self];
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Item *object = type.items[indexPath.row];
    self.detailViewController.detailItem = object;
}

@end
